ArrayUtils.groupBy   A
last analyzed

Complexity

Conditions 1

Size

Total Lines 10
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 10
rs 9.9
c 0
b 0
f 0
cc 1
1
export class ArrayUtils {
2
  public static range(start: number, end: number, step = 1) {
3
    function* generateRange() {
4
      let x = start - step;
5
      while (x <= end - step) {
6
        yield (x += step);
7
      }
8
    }
9
10
    return {
11
      [Symbol.iterator]: generateRange
12
    };
13
  }
14
15
  public static zip<T, U>(left: T[], right: U[]): [T, U][] {
16
    return left.map((value, idx) => [value, right[idx]]);
17
  }
18
19
  public static groupBy<T>(
20
    xs: Array<T>,
21
    key: (x: T) => string
22
  ): { [key: string]: T } {
23
    // Credit: https://stackoverflow.com/a/34890276
24
    return xs.reduce(function(rv, x) {
25
      (rv[key(x)] = rv[key(x)] || []).push(x);
26
      return rv;
27
    }, {});
28
  }
29
}
30